package com.tpvlog.im.gateway.tcp.dispatcher;

import com.tpvlog.im.common.Constants;
import com.tpvlog.im.common.Message;
import com.tpvlog.im.common.Response;
import com.tpvlog.im.gateway.tcp.common.SessionManager;
import com.tpvlog.im.protocal.AuthenticateResponseProto;
import com.tpvlog.im.protocal.MessageSendResponseProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * 作为与分发系统通信的客户端事件处理组件
 */
public class DispatcherInstanceHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        String dispatcherChannelId = channel.remoteAddress().getHostName() + ":" + channel.remoteAddress().getPort();
        DispatcherInstanceManager.getInstance().removeDispatcherInstance(dispatcherChannelId);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;
        Message message = new Message(buffer);
        System.out.println("收到IM-DISPATCHER系统发送来的消息，消息类型为：" + message.getMessageType());

        // 1.如果是Dispathcer系统的响应消息
        if (message.getMessageType() == Constants.MESSAGE_TYPE_RESPONSE) {
            Response response = message.toResponse();
            // 认证响应
            if (response.getRequestType() == Constants.REQUEST_TYPE_AUTHENTICATE) {
                AuthenticateResponseProto.AuthenticateResponse authenticateResponse =
                        AuthenticateResponseProto.AuthenticateResponse.parseFrom(response.getBody());
                String uid = authenticateResponse.getUid();
                System.out.println("收到IM-DISPATHCER系统返回的响应：" + authenticateResponse);

                // 响应SDK客户端
                SocketChannel sdkChannel = SessionManager.getInstance().getSession(uid);
                sdkChannel.writeAndFlush(new Response(response, authenticateResponse.toByteArray()).getBuffer());
                System.out.println("将响应发送到客户端，uid=" + uid + "，客户端地址为：" + sdkChannel);
            }
            // 单聊响应
            else if (response.getRequestType() == Constants.REQUEST_TYPE_SEND_MESSAGE) {
                MessageSendResponseProto.MessageSendResponse messageSendResponse =
                        MessageSendResponseProto.MessageSendResponse.parseFrom(response.getBody());
                long msgId = messageSendResponse.getMessageId();
                System.out.println("收到IM-DISPATHCER系统返回的响应：" + msgId);

                // 响应SDK客户端
                SocketChannel sdkChannel = SessionManager.getInstance().getSession(messageSendResponse.getSenderId());
                sdkChannel.writeAndFlush(new Response(response, messageSendResponse.toByteArray()).getBuffer());
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
